<?php
/**
 * Create By: PhpStorm
 * User: yuanxuncheng
 * File: GetGoods.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\goods;

use app\api\model\dao\Goods;
use app\library\Error;
use app\library\PageBase;
use think\Validate;
use think\Cache;

class SearchGoods extends PageBase
{

    private $objGoods;

    public function __construct()
    {
        parent::__construct();

        $this->objGoods = new Goods();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'q' => 'require',
        ];
        $msg = [
            'q.require' => '搜索关键字必填',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {
        // TODO:业务逻辑
        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            return $this->getRes(Error::ERR_PARAM, $ret);
        }

        $q = $param['q'];

        $arrField = array(
            'goods_id',
            'goods_name',
            'market_price',
            'shop_price',
            'goods_thumb',
            'sale_count',
        );
        $arrCond = array();
        $arrCond['goods_name'] = ['like', "%" . $q . "%"];

        $perpage = isset($param['perpage']) ? intval($param['perpage']) : 0;
        $page = isset($param['page']) ? intval($param['page']) : 0;
        $perpage = max(10, $perpage);
        $page = max(1, $page);
        $offset = ($page - 1) * $perpage;
        $limit = $perpage;

        $counts = $this->objGoods->getCount($arrCond);
        $rets = $this->objGoods->getGoodsByCond($arrCond, $arrField, $offset, $limit, ' create_time desc ');

        if (false === $rets) {
            return $this->getRes(Error::ERR_SYS);
        }

        foreach ($rets as &$ret) {
            $ret['discount'] = '' . round($ret['shop_price'] / $ret['market_price'], 2) * 10;
        }

        $this->data = array(
            'list' => $rets,
            'total' => $counts,
        );
        return $this->getRes();
    }
}
